package com.monkey.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author Wu Tianqiang
 */
public abstract class WebUtils {

    private WebUtils() {
    }

    /**
     * Retrieve client ip address
     *
     * @param request HttpServletRequest
     * @return IP
     */
    public static String clientIp(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    /**
     * Check user client browser is Mobile browser or not
     *
     * @param request HttpServletRequest
     * @return True is mobile browser
     */
    public static boolean isMobileBrowser(HttpServletRequest request) {
        final String userAgent = request.getHeader("user-agent");
        if (StringUtils.isNotEmpty(userAgent)) {
            final String lowerAgent = userAgent.toLowerCase();
            return (lowerAgent.contains("mobile")
                    || lowerAgent.contains("android"));
        }
        return false;
    }

    /**
     * {
     * "code": 0,   0:success  1:fail
     * "data": {
     * "country": "中国",
     * "country_id": "CN",
     * "area": "华中",
     * "area_id": "400000",
     * "region": "湖北省",
     * "region_id": "420000",
     * "city": "武汉市",
     * "city_id": "420100",
     * "county": "",
     * "county_id": "-1",
     * "isp": "教育网",
     * "isp_id": "100027",
     * "ip": "115.156.238.114"
     * }
     * }
     */
    public static String getAddressByClientIp(String ip) {
        String url = "http://ip.taobao.com/service/getIpInfo.php";
        String json = null;
        try {
            json = HttpUtils.doGet(url, ImmutableMap.of("ip", (Object) ip));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }



    /**
     * 对文件流输出下载的中文文件名进行编码 屏蔽各种浏览器版本的差异性
     */
    public static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName) {
        String agent = request.getHeader("USER-AGENT");
        try {
            if (null != agent && agent.contains("MSIE")) {
                pFileName = URLEncoder.encode(pFileName, "utf-8");
            } else {
                pFileName = new String(pFileName.getBytes("utf-8"), "iso8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return pFileName;
    }

    /**
     * 判断request是否是Ajax
     *
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }

    /**
     * 返回json数据
     *
     * @param response
     * @param data
     */
    public static void writeJSON(ServletResponse response, Object data) {
        HttpServletResponse resp = org.apache.shiro.web.util.WebUtils.toHttp(response);
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json; charset=utf-8");
        PrintWriter pw = null;
        try {
            pw = resp.getWriter();
            pw.write(JSON.toJSONString(data));
            pw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 获取系统根路径
     *
     * @param req
     * @return
     */
    public static String getServletBasePath(HttpServletRequest req) {
        StringBuilder baseUrl = new StringBuilder();
        String scheme = req.getScheme();
        int port = req.getServerPort();
        // String servletPath = req.getServletPath ();
        // String pathInfo = req.getPathInfo ();
        baseUrl.append(scheme); // http, https
        baseUrl.append("://");
        baseUrl.append(req.getServerName());
        if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
            baseUrl.append(':');
            baseUrl.append(req.getServerPort());
            baseUrl.append(req.getContextPath());
        }
        return baseUrl.toString();
    }


}